#!/usr/bin/python
# -*- coding: utf-8 -*-

# needed for pack and unpack
import struct
# needed to execute process
import subprocess
# needed to flush
import sys

# positions/buttons on the touch screen:
#
#  1 | 2 | 3
# ---+---+---
#  4 | 5 | 6
# ---+---+---
#  7 | 8 | 9

x = 0
y = 0
z = 0
touchScreenDeviceName = "/dev/input/ts"

# int, int, short, short, int
format = 'iihhi'

def touchScreenpressed(x, y):
  # print "pressed: ",x," ",y
  if x > 530:
    position = 3
  elif x > 300:
    position = 2
  else:
    position = 1

  if y > 315:
    position = position + 6
  elif y > 170:
    position = position + 3

  print "position: ",position
  sys.stdout.flush()
  subprocess.call(\
   ["su user -c /opt/maemo/usr/bin/mplayer-touchcontrol/"+str(position)+".sh &",
   ""], shell=True)

# open file in binary mode
touchScreenDevice = open(touchScreenDeviceName,"rb")
event = touchScreenDevice.read(16)

while event:
  # read single values from the 16 bytes
  (time1, time2, type, code, value) = \
    struct.unpack(format, event)

  # absolute coordinates
  if type == 3:
    if code == 0:
      x = value
    if code == 1:
      y = value
    if code == 2:
      z = value

  # synchronisation of coordinates ready
  # if type == 0 and code == 0:
  #  print x, ":", y

  # touchscreen
  if type == 1 and code == 0x014a:
    # pressed
    if value == 1:
      x = x / 5
      y = 500 - (y / 8)

      #print "pressed : ", x, ":", y
      touchScreenpressed(x, y)

  # read next event
  event = touchScreenDevice.read(16)
